package com.picshare.service;

import com.picshare.event.PhotoUploadedEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.http.HttpSession;

/**
 * SSE监听服务
 * 管理所有活跃的SSE连接，推送照片上传事件
 */
@Service
public class StreamListenerService {
    
    private final ConcurrentMap<String, SseEmitter> activeEmitters = new ConcurrentHashMap<>();
    private final ApplicationEventPublisher eventPublisher;
    
    public StreamListenerService(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }
    
    /**
     * 创建新的SSE连接
     */
    public SseEmitter createEmitter(HttpSession session) {
        String sessionId = session.getId();
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE); // 长时间连接
        
        // 连接完成时移除
        emitter.onCompletion(() -> {
            activeEmitters.remove(sessionId);
        });
        
        // 连接超时时移除
        emitter.onTimeout(() -> {
            activeEmitters.remove(sessionId);
        });
        
        // 连接错误时移除
        emitter.onError(e -> {
            activeEmitters.remove(sessionId);
        });
        
        activeEmitters.put(sessionId, emitter);
        return emitter;
    }
    
    /**
     * 发布照片上传事件
     */
    public void publishPhotoUploaded(com.picshare.model.FileItem photo) {
        PhotoUploadedEvent event = new PhotoUploadedEvent(photo);
        eventPublisher.publishEvent(event);
    }
    
    /**
     * 处理照片上传事件，推送给所有活跃监听器
     */
    public void handlePhotoUploaded(PhotoUploadedEvent event) {
        com.picshare.model.FileItem photo = event.getPhoto();
        
        // 构建要发送的数据
        PhotoStreamData data = new PhotoStreamData(
            photo.getId(),
            photo.getOriginalName(),
            photo.getFileName(),
            photo.isImage(),
            System.currentTimeMillis()
        );
        
        // 推送给所有活跃的监听器
        activeEmitters.forEach((sessionId, emitter) -> {
            try {
                emitter.send(SseEmitter.event()
                    .name("photo-uploaded")
                    .data(data));
            } catch (Exception e) {
                // 发送失败时移除该连接
                activeEmitters.remove(sessionId);
                emitter.completeWithError(e);
            }
        });
    }
    
    /**
     * 移除指定的监听器
     */
    public void removeEmitter(String sessionId) {
        SseEmitter emitter = activeEmitters.remove(sessionId);
        if (emitter != null) {
            emitter.complete();
        }
    }
    
    /**
     * 获取活跃监听器数量
     */
    public int getActiveListenerCount() {
        return activeEmitters.size();
    }
    
    /**
     * SSE数据传输对象
     */
    public static class PhotoStreamData {
        private String id;
        private String originalName;
        private String fileName;
        private boolean image;
        private long timestamp;
        
        public PhotoStreamData(String id, String originalName, String fileName, boolean image, long timestamp) {
            this.id = id;
            this.originalName = originalName;
            this.fileName = fileName;
            this.image = image;
            this.timestamp = timestamp;
        }
        
        // Getters
        public String getId() { return id; }
        public String getOriginalName() { return originalName; }
        public String getFileName() { return fileName; }
        public boolean isImage() { return image; }
        public long getTimestamp() { return timestamp; }
    }
}